import { Card, message, Row, Col, Space } from 'antd';
import { history } from 'umi';
import ProForm, {
  ProFormRadio,
  ProFormUploadButton,
  ProFormTextArea,
  ProFormSelect,
  ProFormDependency,
} from '@ant-design/pro-form';
import { useRequest } from 'umi';
import { useEffect, useState, useRef } from 'react';
import type { FC } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { fakeSubmitForm, queryDetail, update } from './service';
import { hospitalList, queryHospitalAttestation } from '@/services/ant-design-pro/api';
import Address from '../hospital/components/Address';
import styles from './style.less';

const BasicForm: FC<Record<string, any>> = () => {
  const [list, setHospitalList] = useState<Array>([]);
  const [resData, setData] = useState<Object>({});
  const [flag, setFlag] = useState<boolean>(false);
  const [status, setStatus] = useState<Number>(-1);
  const [hosiptalName, setHosiptalName] = useState<String>('');
  const [form] = ProForm.useForm();
  const { run } = useRequest(fakeSubmitForm, {
    manual: true,
    onSuccess: (response) => {
      console.log('response---', response);
      if (response.code == 200) {
        message.success('提交成功');
      } else {
        message.error('提交失败!' + response.message);
      }
    },
  });

  const initData = async (param: object) => {
    const response = await queryHospitalAttestation(param);
    if (response.code == 200) {
      setData(response);
      let data = response.data;
      if (data != null) {
        console.log('data----------', resData);
        // const dz = {};
        // dz.address = data.addressDetail;
        // const province = {};
        // province.label = data.provinceName;
        // province.value = data.provinceCode;
        // dz.province = province;

        // const city = {};
        // city.label = data.cityName;
        // city.value = data.cityCode;
        // dz.city = city;
        let hospital = {
          key: data.hospitalId,
          value: data.hospitalId,
          label: data.name,
        };
        data.hospital = hospital;
        // const district = {};
        // district.label = data.areaName;
        // district.value = data.areaCode;
        // dz.district = district;
        // dz.detailed = data.addressDetail;
        // data.dz = dz;
        if (data.logo) {
          data.upload = [
            {
              uid: '1',
              name: 'icon',
              status: 'done',
              url: 'http://oss.yizuoyiyou.com.cn' + data.logo,
            },
          ];
        }
        if (data.insLicenseCert) {
          data.insLicenseCert = [
            {
              uid: '1',
              name: 'icon',
              status: 'done',
              url: 'http://oss.yizuoyiyou.com.cn' + data.insLicenseCert,
            },
          ];
        }
        if (data.businessLicense) {
          data.businessLicense = [
            {
              uid: '1',
              name: 'icon',
              status: 'done',
              url: 'http://oss.yizuoyiyou.com.cn' + data.businessLicense,
            },
          ];
        }
        if (data.headPic) {
          data.headPicUpload = [
            {
              uid: '1',
              name: 'icon',
              status: 'done',
              url: 'http://oss.yizuoyiyou.com.cn' + data.headPic,
            },
          ];
        }
        data.businessStatus = data.businessStatus + '';
        data.hospitalTypeCode = '10010';
        form.setFieldsValue(data);
        if (data.status == 1 || data.status == 0) {
          setFlag(true);
        }
        setStatus(data.status);
      } else {
        let data = {};
        data.hospitalTypeCode = '10010';
        form.setFieldsValue(data);
      }
    } else {
      message.error('获取数据失败!');
    }
  };

  const initHospitalList = async (param: object) => {
    try {
      const response = await hospitalList(param);
      if (response.code == 200) {
        console.log('respose', response);
        setHospitalList(response.data.list);
      } else {
        message.error('获取数据失败!');
      }
    } catch (error) {
      message.error('获取数据失败' + error);
    }
  };

  useEffect(() => {
    let query = {
      pageNum: 1,
      pageSize: 20,
    };
    initHospitalList(query);
    initData({});
  }, []);

  console.log('detail data', resData);

  const onFinish = async (values: Record<string, any>) => {

    console.log('values11', values);
    const param = { id: 1 };
    setFlag(true);
    setStatus(0);
    try {
      if (values.upload && values.upload.length > 0) {
        if (values.upload[0].response) {
          values.logo = values.upload[0].response.data.url;
        }
        if (values.upload[0].url) {
          let arr = values.upload[0].url.split('http://oss.yizuoyiyou.com.cn');
          values.logo = arr[1];
        }
      }

      if (values.headPicUpload && values.headPicUpload.length > 0) {
        if (values.headPicUpload[0].response) {
          values.headPic = values.headPicUpload[0].response.data.url;
        }
        if (values.headPicUpload[0].url) {
          let arr = values.headPicUpload[0].url.split('http://oss.yizuoyiyou.com.cn');
          values.headPic = arr[1];
        }
      }
      delete values.headPicUpload;

      if (values.businessLicense && values.businessLicense.length > 0) {
        if (values.businessLicense[0].response) {
          values.businessLicense = values.businessLicense[0].response.data.url;
        }
        if (values.businessLicense[0].url) {
          let arr = values.businessLicense[0].url.split('http://oss.yizuoyiyou.com.cn');
          values.businessLicense = arr[1];
        }
      }
      if (values.insLicenseCert.length > 0) {
        if (values.insLicenseCert[0].response) {
          values.insLicenseCert = values.insLicenseCert[0].response.data.url;
        }
        if (values.insLicenseCert[0].url) {
          let arr = values.insLicenseCert[0].url.split('http://oss.yizuoyiyou.com.cn');
          values.insLicenseCert = arr[1];
        }
      }
      if (values.hospital.label) {
        values.hospitalId = values.hospital.value;
      }
      else {
        values.hospitalId = values.hospital;
      }

      values.name = hosiptalName;
      // values.addressDetail = values.dz.detailed;
    } catch (error) {
      console.log('error', error);
    }

    console.log('sessionStorage.getItem(`hosiptalId`)', sessionStorage.getItem(`hosiptalId`));
    if (sessionStorage.getItem(`hosiptalId`) != 0) {
      values.id = sessionStorage.getItem(`hosiptalId`);
    }
    // if (values.dz.province) {
    //   values.provinceName = values.dz.province.label;
    //   values.provinceCode = values.dz.province.value;
    // } else if (values.province) {
    //   values.provinceName = values.province.label;
    //   values.provinceCode = values.province.value;
    // }
    // if (values.dz.city) {
    //   values.cityName = values.dz.city.label;
    //   values.cityCode = values.dz.city.value;
    // } else if (values.city) {
    //   values.cityName = values.city.label;
    //   values.cityCode = values.city.value;
    // }
    // if (values.dz.district) {
    //   values.areaName = values.dz.district.label;
    //   values.areaCode = values.dz.district.value;
    // } else if (values.district) {
    //   values.areaName = values.district.label;
    //   values.areaCode = values.district.value;
    // }
    // delete values.dz;
    delete values.hospital;
    delete values.upload;
    // delete values.city;
    // delete values.district;
    // delete values.province;
    console.log('values', values);
    try {
      const response = await fakeSubmitForm(values);
      if (response.code == 200) {
        message.success('操作成功');
      } else {
        message.error('操作失败!' + response.message);
      }
      window.scrollTo({
        top: 0,
        behavior: 'smooth',
      });
    } catch (error) {
      console.log(error);
    }
  };

  const onChange = (value: object) => {
    //console.log(`selected 1111 `, value);
    // console.log(`selected `, list);
    if (value.hospital) {
      let infoList = list.filter((item) => item.id == value.hospital);

      if (infoList.length > 0) {
        let info = infoList[0];
        console.log(`selected 222 `, info);
        form.setFieldsValue({
          intro: info.intro,
        });
        form.setFieldsValue({
          name: info.name,
        });
        setHosiptalName(info.name);
        // const dz = {};
        // dz.address = info.addressDetail;
        // const province = {};
        // province.label = info.provinceName;
        // province.value = info.provinceCode;
        // dz.province = province;

        // const city = {};
        // city.label = info.cityName;
        // city.value = info.cityCode;
        // dz.city = city;
        // const district = {};
        // district.label = info.areaName;
        // district.value = info.areaCode;
        // dz.district = district;
        // dz.detailed = info.addressDetail;
        let addressDetail = info.provinceName + info.cityName + info.areaName + info.addressDetail;
        form.setFieldsValue({
          addressDetail: addressDetail,
        });
        if (info.logo) {
          let upload = [
            {
              uid: '1',
              name: 'icon',
              status: 'done',
              url: 'http://oss.yizuoyiyou.com.cn' + info.logo,
            },
          ];
          form.setFieldsValue({
            upload: upload,
          });
        }
        else {
          form.setFieldsValue({
            upload: [],
          });
        }
        if (info.headPic) {
          let headPicUpload = [
            {
              uid: '1',
              name: 'icon',
              status: 'done',
              url: 'http://oss.yizuoyiyou.com.cn' + info.headPic,
            },
          ];
          form.setFieldsValue({
            headPicUpload: headPicUpload,
          });
        }
        else {
          form.setFieldsValue({
            headPicUpload: [],
          });
        }
      }
    }
  };

  const formItemLayout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 14 },
  };

  return (
    <PageContainer content="">
      <Card bordered={false}>
        <ProForm
          form={form}
          onValuesChange={(changeValues) => onChange(changeValues)}
          style={{ margin: 'auto', marginTop: 8 }}
          name="basic"
          layout="horizontal"
          disabled={flag}
          // initialValues={data}
          onFinish={onFinish}
          {...formItemLayout}
          submitter={{
            render: (props, doms) => {
              //不通过或者未提交
              if (status == -1 || status == 2) {
                return (
                  <Row>
                    <Col span={14} offset={4}>
                      <Space>{doms}</Space>
                    </Col>
                  </Row>
                );
              }
            },
          }}
        >
          {status == 0 ? (
            <div className={styles.tips}>温馨提示：正在审核中，请耐心等待，有问题联系运营人员</div>
          ) : null}
          <ProFormRadio.Group
            rules={[
              {
                required: true,
                message: '请选择机构类型',
              },
            ]}
            options={[
              {
                value: '10010',
                label: '医院',
              },
              {
                value: '1',
                label: '医院科室',
                disabled: true,
              },
            ]}
            label="机构类型"
            name="hospitalTypeCode"
          />
          <ProFormSelect
            width="md"
            name="hospital"
            label="医院名称"
            rules={[
              {
                required: true,
                message: '请选择医院名称',
              },
            ]}
            placeholder="请选择医院名称"
            showSearch
            request={async ({ keyWords }) => {
              let query = {
                likeQuery: {
                  name: keyWords,
                },
                pageNum: 1,
                pageSize: 20,
              };
              initHospitalList(query);
              return hospitalList(query).then(({ data }) => {
                return data.list.map((item) => {
                  return {
                    label: item.name,
                    value: item.id,
                  };
                });
              });
            }}
          />
          <ProFormUploadButton
            name="upload"
            label="医院logo"
            max={1}
            fieldProps={{
              name: 'file',
              listType: 'picture-card',
            }}
            action="/api/file/upload"
            rules={[
              {
                required: true,
                message: '请上传医院logo',
              },
            ]}
          />
          <ProFormUploadButton
            name="headPicUpload"
            label="医院门头图"
            max={1}
            fieldProps={{
              name: 'file',
              listType: 'picture-card',
            }}
            action="/api/file/upload"
          />
          {/* <ProFormText
            width="md"
            label="医院全称"
            name="fullName"
            rules={[
              {
                required: true,
                message: '请输入医院全称',
              },
            ]}
            placeholder="请输入医院全称"
          /> */}

          <ProFormTextArea name="addressDetail" label="医院地址" placeholder="请输入医院地址"
            rules={[
              {
                required: true,
                message: '请输入医院地址',
              },
            ]} />
          {/* <ProFormRadio.Group
            request={async () => {
              const params = { dictCode: 'grade' };
              return queryDictList(params).then(({ data }) => {
                return data.map((item) => {
                  return {
                    label: item.itemName,
                    value: item.itemName,
                  };
                });
              });
            }}
            label="医院等级"
            name="grade"
          /> */}
          <ProFormTextArea
            name="intro"
            label="医院简介"
            placeholder="请输入医院简介"
            rules={[
              {
                required: true,
                message: '请输入医院简介',
              },
            ]}
          />

          <ProFormTextArea name="visitInfo" label="门诊时间(选填)" placeholder="请输入门诊时间" />
          {/* <ProForm.Item label="挂号攻略" name="registration">
            <RichText />
          </ProForm.Item> */}
          <ProFormTextArea
            name="registration"
            label="挂号攻略(选填)"
            placeholder="请输入挂号攻略"
          />
          <ProFormUploadButton
            name="businessLicense"
            label="营业执照(选填)"
            max={1}
            fieldProps={{
              name: 'file',
              listType: 'picture-card',
            }}
            action="/api/file/upload"
            rules={[
              {
                required: false,
                message: '请上传营业执照',
              },
            ]}
          />
          <ProFormUploadButton
            name="insLicenseCert"
            label="医疗机构执业许可证"
            max={1}
            fieldProps={{
              name: 'file',
              listType: 'picture-card',
            }}
            action="/api/file/upload"
            rules={[
              {
                required: true,
                message: '请上传医疗机构执业许可证',
              },
            ]}
          />
          {status == 2 ? <ProFormTextArea name="failReason" label="未通过原因" disabled /> : null}
          {/* <ProFormRadio.Group
            request={async () => {
              const params = { dictCode: 'operationNature' };
              return queryDictList(params).then(({ data }) => {
                return data.map((item) => {
                  return {
                    label: item.itemName,
                    value: item.itemName,
                  };
                });
              });
            }}
            label="运营性质"
            name="operationNature"
          />
          <ProFormRadio.Group
            request={async () => {
              const params = { dictCode: 'professionalNature' };
              return queryDictList(params).then(({ data }) => {
                return data.map((item) => {
                  return {
                    label: item.itemName,
                    value: item.itemName,
                  };
                });
              });
            }}
            label="专业性质"
            name="professionalNature"
          /> 
          <ProFormTextArea name="excellentDept" label="特色科室" placeholder="请输入特色科室" />
          <ProFormRadio.Group
            options={[
              {
                value: '0',
                label: '营业',
              },
              {
                value: '1',
                label: '歇业',
              },
            ]}
            label="营业状态"
            name="businessStatus"
          />*/}
        </ProForm>
      </Card>
    </PageContainer>
  );
};

export default BasicForm;
